package com.wondertek.poms.core.service.impl;

import com.sun.imageio.plugins.common.ImageUtil;
import com.wondertek.oes.sso.common.util.StringUtil;
import com.wondertek.poms.common.service.impl.ServiceImpl;
import com.wondertek.poms.core.service.IImageService;
import com.wondertek.poms.core.service.ISystemConfigService;
import com.wondertek.poms.core.utils.FileUploadUtil;
import com.wondertek.poms.dao.po.Content;
import com.wondertek.poms.dao.po.DisplayFile;
import com.wondertek.poms.dao.po.Image;
import com.wondertek.poms.dao.repo.IContentDao;
import com.wondertek.poms.dao.repo.IDisplayFileDao;
import com.wondertek.poms.dao.repo.IImageDao;
import com.wondertek.poms.dao.vo.ImageVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;


/**
 * @author chenjijiang
 * @description
 */
@Service
@Slf4j
public class ImageServiceImpl extends ServiceImpl<Image, Long> implements IImageService {
	private final static Long DEFUALT_MIN_SIZE = 105542L;

	@Autowired
	private IImageDao imageDao;
	@Autowired
	private IContentDao contentDao;
	@Autowired
	private IDisplayFileDao displayFileDao;

	@Autowired
	private ISystemConfigService systemConfigService;

	@Override
	public Image createImage(Image image) {
		if (image.getFileType() != null
				&& image.getFileType().indexOf(".") >= 0) {
			image.setFileType(image.getFileType().substring(image.getFileType().indexOf(".") + 1));
		}
		// 图片大小处理
		if (image.getFileSize() == null
				|| image.getFileSize().longValue() <= 0L) {
			image.setFileSize(DEFUALT_MIN_SIZE);
		}
		return image;
	}

	@Override
	public boolean saveAndDelContImage(Content content, List<Image> imageList) {
		String tagetPath = systemConfigService.findAllBykey("syncFile_basePath").getValue()+ "/zhengshi";
		//	String tagetPath = "D://jlpImage";
		String contentId = content.getContentId().toString();
		Map<Long, Image> imageMap = new HashMap<Long, Image>(1);
		StringBuffer sb = new StringBuffer ();
		try{
			if (imageList != null && imageList.size() > 0) {
				for (int i = 0; i < imageList.size(); i++) {
					Image sImage = imageList.get(i);
					if ( sImage== null || sImage.getTags() == null || "".equals(sImage.getTags())) {
						sImage.setTags("small");
					}
					boolean isNewImage = false;
					if(sImage.getImgId() == null && sImage.getFileId() != null && sImage.getFileId().startsWith("SWFUpload_")){
						isNewImage = true;
					}else if(sImage.getImgId() == null){
						return false;
					}
					if(sImage != null && sImage.getImgId() != null){


						String name = sImage.getName() + "." + sImage.getFileType();
						String imageSrc =tagetPath
								+ File.separator + contentId.substring(0,4)
								+ File.separator + contentId.substring(4,7)
								+ File.separator + contentId.substring(7,10)
								+ File.separator + contentId
								+File.separator + "display"+File.separator+name;
						sImage.setSrc(imageSrc);
					}

					sImage.setDescription(sImage.getTags());
					sImage.setName(sImage.getName().trim());
					sImage = this.save(sImage);

					if (isNewImage) {
						String newPath = tagetPath
								+ File.separator + contentId.substring(0,4)
								+ File.separator + contentId.substring(4,7)
								+ File.separator + contentId.substring(7,10)
								+ File.separator + contentId
								+File.separator + "display"+File.separator;
						String newName = sImage.getName() + "." + sImage.getFileType();
						String oldPath = sImage.getSrc().replace(".", "*All.");
						File oldFile = new File(oldPath);
						boolean result = FileUploadUtil.copyFileFilter(oldPath, newPath + newName);
						if (oldFile.exists()
								&& !oldFile.delete()) {
							log.info("Resource Leaking:  Could not remove uploaded file '" + oldFile.getCanonicalPath() + "'.");
						}
						if(!result){
							return false;
						}
						String imageSrc  = newPath + File.separator + newName;
						sImage.setSrc(imageSrc);
						sImage.setDescription(sImage.getTags());
						save(sImage);
						DisplayFile displayFile = new DisplayFile();
						displayFile.setDpFileId(sImage.getImgId().toString());
						displayFile.setDpAdapType("0");
						displayFile.setDpFileName(sImage.getName() + "." + sImage.getFileType());
						displayFile.setDpFileType("3");
						displayFile.setDpUsageCode("0");
						displayFile.setDpUseType("0");
					  	displayFile.setDpPixel("0");
						displayFile.setContentId(contentId);
						displayFileDao.save(displayFile);
						String filePath = systemConfigService.findAllBykey("IMAGE_PATH").getValue()+ File.separator + "temp"+File.separator+sImage.getName()+"."+sImage.getFileType();
						FileUploadUtil.delFile(filePath);
					}
					imageMap.put(sImage.getImgId(), sImage);
					sb.append(sImage.getImgId() + ",");
				}
			}
			String deleteImages = content.getImages();
			String imageIds = StringUtil.longArrayToString(StringUtil.stringToLongArray(sb));
			content.setImages(imageIds);
			contentDao.save(content);

			// 筛选删除栏目图片
			if(deleteImages != null && !"".equals(deleteImages)){
				List<Long> imageIdList = new ArrayList<Long>();
				String[] ids = deleteImages.split(",");
				if(ids != null && ids.length > 0){
					for(int i = 0 ; i < ids.length; i ++){
						if(ids[i] != null && StringUtil.isNumber(ids[i])){
							imageIdList.add(Long.parseLong(ids[i]));
						}
					}
				}
				//筛选删除
				if(imageMap != null
						&& imageMap.size() > 0
						&& imageIdList != null
						&& imageIdList.size() > 0){
					for(Iterator<Long> it = imageMap.keySet().iterator(); it.hasNext(); ){
						Long imageId = it.next();
						if(imageIdList.contains(imageId)){
							imageIdList.remove(imageId);
						}
					}
				}

				if(imageIdList != null && imageIdList.size() > 0 ){
					List<Image> deleteList = new ArrayList<Image> ();
					for(Iterator<Long> it = imageIdList.iterator(); it.hasNext(); ){
						Long imageId = it.next();
						Image image = this.get(imageId);
						if(image != null && image.getImgId() != null){
							String name = image.getName().toString()+ "." + image.getFileType();
							String fullPath =tagetPath
									+ File.separator + contentId.substring(0,4)
									+ File.separator + contentId.substring(4,7)
									+ File.separator + contentId.substring(7,10)
									+ File.separator + contentId
									+File.separator + "display"+ File.separator + name;
							FileUploadUtil.delFile(fullPath);
							deleteList.add(image);
						}
					}
					for (Image image:deleteList) {
						deleteById(image.getImgId());
					}
					for(Image image : deleteList){
						List <DisplayFile> list = displayFileDao.findAllByContentId(contentId);
						for(DisplayFile dis : list){
							if(dis.getDpFileId().equals(image.getImgId().toString())){
								if(dis.getId()!=null){
									displayFileDao.deleteById(dis.getId());
								}
							}
						}
					}
				}
			}
		}catch(Exception e){
			log.error("",e);
			log.error("",e);
			return false;
		}
		return true;
	}

	@Override
	public List<ImageVo> getAllImages(String contId) {
		List<ImageVo> imagesList = new ArrayList<ImageVo>();
		if (StringUtils.isNotBlank(contId)) {
			//原图地址
			String imgSourcePath = "/nas/video/cont/zhengshi/"
					+ contId.substring(0, 4) + "/" + contId.substring(4, 7)
					+ "/" + contId.substring(7, 10) + "/" + contId
					+ "/display/";
			//转图地址
			String imgPath = "/nas/sj_nas_poms/cmvideo/image/"
					+ contId.substring(0, 4) + "/" + contId.substring(4, 7)
					+ "/" + contId.substring(7, 10) + "/" + contId
					+ "/display/";
			imagesList=addImageVo(imagesList,contId,imgSourcePath);
			imagesList=addImageVo(imagesList,contId,imgPath);
		}
		return imagesList;
	}

	public List<ImageVo> addImageVo(List<ImageVo> list,String contId,String imgPath){
		//测试和生产环境使用
		File f = new File(imgPath);
		log.info("PrdContServiceImpl#getImages_imgPath"+imgPath);
		if (f.exists() && f.isDirectory()) {
			File[] fs = f.listFiles();
			log.info("PrdContServiceImpl#getImages_File.length"+fs.length);
			for (int i = 0; i < fs.length; i++) {
				ImageVo img = new ImageVo();
				img.setName(fs[i].getName());
				img.setSrc(fs[i].getAbsolutePath());
				// 图片大小,单位KB,保留一位小数
				img.setImgSize((float) Math.round((fs[i].length() / 1024.0f) * 10) / 10);
				list.add(img);
			}
		}
		return list;
	}


	@Override
	public List<ImageVo> getImagesWithoutWebp(String contId) {
		List<ImageVo> imagesList = new ArrayList<ImageVo>();
//		if (StringUtils.isNotBlank(contId)) {
//			String imgPath = "/nas/video/cont/zhengshi/"
//					+ contId.substring(0, 4) + "/" + contId.substring(4, 7)
//					+ "/" + contId.substring(7, 10) + "/" + contId
//					+ "/display/";
//			//测试和生产环境使用
//			File f = new File(imgPath);
//			log.info("PrdContServiceImpl#getImages_imgPath"+imgPath);
//			if (f.exists() && f.isDirectory()) {
//				File[] fs = f.listFiles();
//				log.info("PrdContServiceImpl#getImages_File.length"+fs.length);
//				for (File file: fs) {
//					//展示原图
//					ImageVo img = new ImageVo();
//					img.setName(file.getName());
//					img.setSrc(toBase64(file));
//					imagesList.add(img);
//				}
//			}
//		}
//		本地测试使用
		if(imagesList.size()==0){
			ImageVo img = new ImageVo();
			img.setName("2.jpg");
			img.setSrc(toBase64(new File("D://test/2.jpg")));
			imagesList.add(img);
			img.setName("1.jpg");
			img.setSrc(toBase64(new File("D://test/1.jpg")));
			imagesList.add(img);
			img.setName("3.jpg");
			img.setSrc(toBase64(new File("D://test/3.jpg")));
			imagesList.add(img);
			img.setName("4.jpg");
			img.setSrc(toBase64(new File("D://test/4.jpg")));
			imagesList.add(img);
		}
		return imagesList;
	}
	public  String toBase64(File file){
		log.info("ImageServiceImpl#toBase64_file"+file.getName());
		try{
			// 构造Image对象
			BufferedImage src = ImageIO.read(file);
			int width;
			int height;
			float wi = src.getWidth();
			float he = src.getHeight();
			float wProportion=wi/1300;
			float hProportion=he/680;
			if(wProportion>hProportion){
				width=(int) (wi/wProportion);
				height= (int) (he/wProportion);
			}else{
				width= (int) (wi/hProportion);;
				height= (int) (he/hProportion);
			}
			// 缩小边长
			BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			// 绘制 缩小 后的图片
			tag.getGraphics().drawImage(src, 0, 0,  width,  height, null);
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			int i= file.getAbsolutePath().lastIndexOf(".");
			if(i!=-1){
				String suffix=file.getAbsolutePath().substring(i+1);
				boolean flag = ImageIO.write(tag,suffix, out);
				if(flag){
					byte[] data= out.toByteArray();
					BASE64Encoder encoder = new BASE64Encoder();
					return encoder.encode(data);
				}
			}
		}catch (IOException e){
			log.error("图片转base64失败",e);
		}
		return null;
	}

	@Override
	public Image deleteLogic(Long id) {
		return null;
	}

	@Override
	public Image merge(Image model) {
		return null;
	}
}
